from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
import json
import pymysql
from apps.api.mapper.sql_connect import match_identity,register_user


# Create your views here.

# 登录逻辑
@csrf_exempt
def login(request):
    form = json.loads(request.body)
    # 接受账号密码。
    if request.method == 'POST':
        username = form['username']
        password = form['password']

        result = match_identity(username, password)
        if result:
            status_code = 1
            message = "success"
        else:
            status_code = 0
            message = "fail"

    else:
        # 请求方式错误
        status_code = '404'
        message = "请求方式错误"

    # 返回数据
    response = {
        'status_code': status_code,
        'message': message
    }
    return JsonResponse(response)


# 注册逻辑
@csrf_exempt
def register(request):
    form = json.loads(request.body)
    # 接受账号密码。
    if request.method == 'POST':
        username = form['username']
        password = form['password']

        result = register_user(username, password)
        if result:
            status_code = 1
            message = "success"
        else:
            status_code = 0
            message = "fail"

    else:
        # 请求方式错误
        status_code = '404'
        message = "请求方式错误"

    # 返回数据
    response = {
        'status_code': status_code,
        'message': message
    }
    return JsonResponse(response)
